package com.antler.smt.portal.service.impl;

import com.antler.smt.constant.DateTimeConstant;
import com.antler.smt.constant.ImgTypeConstant;
import com.antler.smt.constant.OrderConstant;
import com.antler.smt.entity.*;
import com.antler.smt.enums.ResultCodeEnum;
import com.antler.smt.portal.mapper.*;
import com.antler.smt.portal.utils.RedisUtil;
import com.antler.smt.request.admin.GetSupplierListReq;
import com.antler.smt.request.portal.MemberReq;
import com.antler.smt.request.portal.OrderLogisticsReq;
import com.antler.smt.request.portal.SupplierPersonReq;
import com.antler.smt.response.admin.GetOrderListResp;
import com.antler.smt.response.admin.GetSupplierListResp;
import com.antler.smt.response.base.Result;
import com.antler.smt.response.portal.GetImgResp;
import com.antler.smt.response.portal.SupplierShowTimeResp;
import com.antler.smt.service.portal.SupplierService;
import com.antler.smt.utils.DateUtil;
import com.antler.smt.utils.LogUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mysql.cj.x.protobuf.MysqlxCrud;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 服务商实现接口
 *
 * @author zhangyi
 * @date 2018/3/29 18:03
 */
@Service
public class SupplierServiceImpl implements SupplierService {

    /**
     * 日志
     */
    private static Logger log = LogUtil.get();

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderEntityMapper orderEntityMapper;

    @Autowired
    private SupplierInfoMapper supplierInfoMapper;

    @Autowired
    private OrderLogisticsEntityMapper orderLogisticsEntityMapper;

    @Autowired
    private MemberEntityMapper memberEntityMapper;

    @Autowired
    private SupplierEntityMapper supplierEntityMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private AttachmentEntityMapper attachmentEntityMapper;

    @Autowired
    private RequirementEntityMapper requirementEntityMapper;

    @Autowired
    private SupplierPictureInfoMapper supplierPictureInfoMapper;

    @Autowired
    private SupplierPictureEntityMapper supplierPictureEntityMapper;

    /**
     * 获取当前订单下的服务商实体
     *
     * @param orderEntity 请求订单实体
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<SupplierEntity> getSupplierInfo(OrderEntity orderEntity) {

        Result result = null;

        //获取服务商id
        long supplierIdByPrimaryId = orderInfoMapper.getSupplierIdByPrimaryId(orderEntity.getId());

        SupplierEntity supplierEntity = new SupplierEntity();
        supplierEntity.setId(supplierIdByPrimaryId);

        //查询此服务商
        GetSupplierListResp supplier = supplierInfoMapper.selectSupplierByKey(supplierEntity);

        //获取其会员信息
        MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(supplier.getMemberId());

        List list = new LinkedList();

        list.add(supplier);
        list.add(memberEntity);
        result = new Result(list);

        return result;
    }

    /**
     * 获取当前的服务商实体
     *
     * @param memberId
     * @return
     */
    @Override
    public Result<GetSupplierListResp> getSupplier(long memberId) {
        Result result = null;

        //服务商实体
        SupplierEntity supplierEntity = new SupplierEntity();
        supplierEntity.setMemberId(memberId);

        GetSupplierListResp supplierInfo = supplierInfoMapper.selectSupplierByKey(supplierEntity);

        //获取会员实体
        MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(memberId);

        List resultInfoList = new ArrayList();

        resultInfoList.add(supplierInfo);
        resultInfoList.add(memberEntity);

        result = new Result(resultInfoList);
        return result;
    }

    /**
     *  获取其当前服务商下的订单列表
     *
     * @param memberId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<GetOrderListResp> getSupplierOrderList(long memberId) {
        Result result = null;

        //获取其服务商实体
        SupplierEntity supplierEntity = new SupplierEntity();
        supplierEntity.setMemberId(memberId);
        GetSupplierListResp getSupplierListResp = supplierInfoMapper.selectSupplierByKey(supplierEntity);

        //获取其订单列表
        List<GetOrderListResp> supplierOrderList = orderInfoMapper.getSupplierOrderList(getSupplierListResp.getId());

        List<GetOrderListResp> supplierOrderListBack = new ArrayList<>();
        if(supplierOrderList.size() == 0){
            for(int i = 0; i < supplierOrderList.size(); i++){
                supplierOrderList.get(i).setRealName("暂无服务商信息！");
            }
        }else{
            for(int i = 0; i < supplierOrderList.size(); i++){
                GetOrderListResp orderListResp = supplierOrderList.get(i);
                //插入文件
                AttachmentEntity attachmentEntity = attachmentEntityMapper.selectByPrimaryKey(supplierOrderList.get(i).getTestReportAttachmentId());
                if(attachmentEntity != null) {
                    supplierOrderList.get(i).setReportName(attachmentEntity.getFileName());
                }
                //插入实际和预计交货时间
                if(orderListResp.getStatus() > OrderConstant.ORDER_WAIT_SURE_PAYMENT) {
                    Long orderId = orderListResp.getId();
                    OrderEntity orderEntity = orderEntityMapper.selectByPrimaryKey(orderId);
                    //支付审核时间
                    Date payAuditTime = orderEntity.getPayAuditTime();
                    RequirementEntity requirementEntity = requirementEntityMapper.selectByPrimaryKey(orderEntity.getRequirementId());
                    //获取交期/小时
                    Integer endline = requirementEntity.getEndline();
                    Long endTime = new Long(endline * 60 * 60 * 1000);
                    //预定时间：交期+项目专员审核金额后的时间
                    supplierOrderList.get(i).setReserveTime(DateUtil.stampToDate(endTime + payAuditTime.getTime()));
                    //实际交货时间：采购商收货的时间
                    if (OrderConstant.ORDER_WAIT_COMMENT <= orderEntity.getStatus() && !orderEntity.getStatus().equals(OrderConstant.ORDER_FAIL)) {
                        supplierOrderList.get(i).setActualTime(orderEntity.getUpdateTime());
                    }
                }
                if(!orderListResp.getStatus().equals(OrderConstant.ORDER_FAIL) &&
                        !orderListResp.getStatus().equals(OrderConstant.ORDER_WAIT_JOIN_SUPPLIER) &&
                        !orderListResp.getStatus().equals(OrderConstant.ORDER_WAIT_PAYMENT) &&
                        !orderListResp.getStatus().equals(OrderConstant.ORDER_WAIT_SURE_PAYMENT)) {
                    supplierOrderListBack.add(supplierOrderList.get(i));
                }
            }
        }

        result = new Result(supplierOrderListBack);

        return result;
    }

    /**
     * 服务商入驻
     *
     * @param request
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> updateSupplierSettled(GetSupplierListReq request, Long memberId, String code) {
        Result result = null;

        //服务商实体
        SupplierEntity supplierEntity = new SupplierEntity();

        //添加会员id
        supplierEntity.setMemberId(memberId);

        //添加公司名称
        supplierEntity.setCompanyName(request.getCompanyName());

        //添加统一社会信用码
        supplierEntity.setCreditCode(request.getCreditCode());

        //添加公司地址
        supplierEntity.setDetailAddress(request.getDetailAddress());

        //添加法人
        supplierEntity.setLegalPerson(request.getLegalPerson());

        //添加成立日期
        supplierEntity.setFoundTime(request.getFoundTime());

        //添加对公账户
        supplierEntity.setPublicAccount(request.getPublicAccount());

        //添加营业执照id
        supplierEntity.setBusinessLicenseAttachmentId(request.getBusinessLicenseAttachmentId());

        //添加银行开户许可证
        supplierEntity.setBankPermitAttachmentId(request.getBankPermitAttachmentId());

        //添加生产线设备信息
        supplierEntity.setProductInfo(request.getProductInfo());

        //添加产能信息
        supplierEntity.setCapacity(request.getCapacity());

        //添加班组
        supplierEntity.setClassInfo(request.getClassInfo());

        //添加生产优势所长
        supplierEntity.setProductAdvantage(request.getProductAdvantage());

        //添加响应周期
        supplierEntity.setResonseCycle(request.getResonseCycle());

        //添加交期
        supplierEntity.setFinishCycle(request.getFinishCycle());

        //添加品控
        supplierEntity.setQualityControl(request.getQualityControl());

        //添加工艺水平
        supplierEntity.setTechnology(request.getTechnology());
        //添加生产作业图片id
        //添加整体加工厂图片id
        //添加成功样品信息
        //添加联系人
        supplierEntity.setLinkMan(request.getLinkMan());

        //添加电子邮箱
        supplierEntity.setLinkEmail(request.getLinkEmail());

        //添加联系电话
        supplierEntity.setLinkPhone(request.getLinkPhone());

        //添加时间
        supplierEntity.setCreateTime(DateUtil.stampToDate(System.currentTimeMillis()));
        supplierEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //添加入驻状态 入驻审核状态 0未申请 1已申请未审核 2审核通过 3审核未通过
        supplierEntity.setSettledAuditResult(1);

        //添加入住申请时间
        supplierEntity.setSettledAuditApplyTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //获取用户实体
        MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(memberId);
        //验证码校验
        String localCode = redisUtil.get(String.valueOf(memberId));

        if(localCode.equals(code)){
            //服务商写入
            int i = supplierInfoMapper.updateSupplierInfo(supplierEntity);
            if(0 == i){
                result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
            }else{
                result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
            }
        }else {
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }
        return result;
    }

    /**
     *  获取当前完成优质订单数量
     *
     * @param memberId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<Integer> excellentConunt(Long memberId) {
        SupplierEntity supplierEntity = new SupplierEntity();

        supplierEntity.setMemberId(memberId);

        //获取当前服务商
        GetSupplierListResp supplierList = supplierInfoMapper.selectSupplierByKey(supplierEntity);

        //获取订单列表
        List<GetOrderListResp> supplierOrderList = orderInfoMapper.getSupplierOrderList(supplierList.getId());

        return new Result(supplierOrderList.size());
    }

    /**
     * 服务商发货，修改订单状态，并存储订单信息
     *
     * @param orderId 订单id
     * @param request 订单物流实体
     * @return 状态信息
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> sendGoods(Long orderId, OrderLogisticsReq request) {
        Result result = null;

        //创建订单实体
        OrderEntity orderEntity = new OrderEntity();

        //添加主键
        orderEntity.setId(orderId);

        //更新时间
        orderEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));

        //进度 0待对接服务商 1待付款 2待确认付款 3待生产完成  4待收货 6待评价 7待付款给服务商 8结束 100驳回
        orderEntity.setStatus(OrderConstant.ORDER_WAIT_GIVEGOODS);

        int orderCount = orderEntityMapper.updateByPrimaryKeySelective(orderEntity);

        //创建快递物流实体
        OrderLogisticsEntity orderLogisticsEntity = new OrderLogisticsEntity();

        //添加快递运单号
        orderLogisticsEntity.setOrderId(orderId);

        //添加快递公司id
        orderLogisticsEntity.setPostCompanyId(request.getPostCompanyId());

        //添加快递方式(自提，快递)
        orderLogisticsEntity.setPostType(request.getPostType());

        //添加快递
        orderLogisticsEntity.setPostCompanyName(request.getPostCompanyName());

        //添加运单号
        orderLogisticsEntity.setTrackingNo(request.getTrackingNo());

        //添加发货方式
        orderLogisticsEntity.setDeliverType(Byte.parseByte("1"));

        //添加时间
        orderLogisticsEntity.setCreateTime(DateUtil.stampToDate(System.currentTimeMillis()));
        orderLogisticsEntity.setUpdateTime(DateUtil.stampToDate(System.currentTimeMillis()));



        int orderLogisticsCount = orderLogisticsEntityMapper.insertSelective(orderLogisticsEntity);

        if(0 == (orderCount & orderLogisticsCount)){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }
        return result;
    }

    /**
     *  服务商的个人信息编辑
     *
     * @param request
     * @param memberId
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> editMemberSupplierInfo(SupplierPersonReq request,Long memberId) {
        Result result = null;

        //创建服务商实体
        SupplierEntity supplierEntity = new SupplierEntity();

        //添加会员id
        supplierEntity.setMemberId(memberId);

        Long id = supplierInfoMapper.selectSupplierByKey(supplierEntity).getId();

        //添加主键
        supplierEntity.setId(id);

        //添加公司名称
        supplierEntity.setCompanyName(request.getCompanyName());

        //添加统一信用社代码
        supplierEntity.setCreditCode(request.getCreditCode());

        //添加公司地址
        supplierEntity.setDetailAddress(request.getDetailAddress());

        //添加法人
        supplierEntity.setLegalPerson(request.getLegalPerson());

        //添加成立日期
        supplierEntity.setFoundTime(request.getFoundTime());

        //添加联系人
        supplierEntity.setLinkMan(request.getLinkMan());

        //添加联系电话
        supplierEntity.setLinkPhone(request.getLinkPhone());

        //添加联系邮箱
        supplierEntity.setLinkEmail(request.getLinkEmail());

        //添加对公账户
        supplierEntity.setPublicAccount(request.getPublicAccount());

        //创建会员实体
        MemberEntity memberEntity = new MemberEntity();

        //添加主键id
        memberEntity.setId(memberId);

        //添加昵称
        memberEntity.setNickName(request.getNickName());

        //添加头像id
        memberEntity.setHeadImageAttachmentId(request.getHeadImageAttachmentId());

        int i = memberEntityMapper.updateByPrimaryKeySelective(memberEntity);

        int j = supplierEntityMapper.updateByPrimaryKeySelective(supplierEntity);

        if((i & j) == 0){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR);
        }else{
            result = new Result(ResultCodeEnum.OPERATION_SUCCESS);
        }

        return result;
    }

    /**
     *  优质加工厂的申请
     *
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = DateTimeConstant.MINUTE_S, rollbackFor = Exception.class)
    public Result<ResultCodeEnum> excellent(Long memberId) {
        Result result = null;

        SupplierEntity supplierEntity = new SupplierEntity();

        supplierEntity.setMemberId(memberId);

        //获取当前服务商
        GetSupplierListResp supplierList = supplierInfoMapper.selectSupplierByKey(supplierEntity);

        //获取订单列表
        List<GetOrderListResp> supplierOrderList = orderInfoMapper.getSupplierOrderList(supplierList.getId());

        int orderCount = 0;

        //判断是否完成订单（以状态8完成为准）
        for(GetOrderListResp g : supplierOrderList){
            if(g.getStatus().equals(OrderConstant.ORDER_END)){
                orderCount++;
            }
        }

        //当完成3笔订单时候可以申请优质服务商
        if (orderCount < OrderConstant.ORDER_COUNT){
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR,"优质订单数不够！");
        }else{
            result = new Result(OrderConstant.APPLY_SUCCESS);
            //更改审核状态 优质服务商认证状态：0未申请 1已经申请未审核 2审核通过 3审核未通过
            supplierEntity.setAuditResult(1);
            supplierEntity.setAuditApplyTime(DateUtil.stampToDate(System.currentTimeMillis()));
            supplierInfoMapper.updateSupplierInfo(supplierEntity);
        }
        return result;
    }

    /**
     *  查条件询优质服务商
     *
     * @param request
     * @return
     */
    @Override
    public  Result<GetSupplierListResp> selectExcellentSupplier(GetSupplierListReq request) {
        Result result = null;
        PageHelper.startPage(request.getPageCurrent(), request.getPageSize());
        Page<GetSupplierListResp> listSupplierListResps = supplierInfoMapper.selectExcellentSupplier(request);

        for(int i = 0; i < listSupplierListResps.size(); i++){
            MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(
                                        listSupplierListResps.get(i).getMemberId());
            listSupplierListResps.get(i).setNickName(memberEntity.getNickName());

            GetSupplierListResp supplierListResp = listSupplierListResps.get(i);
            List<GetImgResp> supplierListInfo = supplierPictureInfoMapper.getSupplierListInfo(supplierListResp.getId());
            boolean flag = true;
            for(GetImgResp imgResp : supplierListInfo){
                //获取全景加工厂图
                if(imgResp.getType().equals(2)){
                    listSupplierListResps.get(i).setOverallView(imgResp.getImgName());
                    flag = false;
                    break;
                }

            }

            if(flag){
                listSupplierListResps.get(i).setOverallView(attachmentEntityMapper.selectByPrimaryKey(new Long(ImgTypeConstant.DEFALUT_SUPPLIER_IMG)).getFileName());
            }
        }
        if (listSupplierListResps != null) {
            PageInfo<GetSupplierListResp> supplierListPageInfo = new PageInfo(listSupplierListResps);
            result = new Result(supplierListPageInfo);
        } else {
            result = new Result(ResultCodeEnum.QUERY_DATA_ERROR, "查询优质服务商数据为空！");
        }
        return result;
    }

    /**
     *  根据昵称查询优质加工厂信息
     *
     * @param request
     * @return
     */
    @Override
    public  Result<GetSupplierListResp> selectExcellentSupplierByNickName(MemberReq request) {
        Result result = null;
        PageHelper.startPage(request.getPageCurrent(), request.getPageSize());
        Page<GetSupplierListResp> listSupplierListResps = supplierInfoMapper.selectExcellentSupplierByNickName(request.getNickName());

        for(int i = 0; i < listSupplierListResps.size(); i++){
            MemberEntity memberEntity = memberEntityMapper.selectByPrimaryKey(
                    listSupplierListResps.get(i).getMemberId());
            listSupplierListResps.get(i).setNickName(memberEntity.getNickName());
        }
        if (listSupplierListResps != null) {
            PageInfo<GetSupplierListResp> supplierListPageInfo = new PageInfo(listSupplierListResps);
            result = new Result(supplierListPageInfo);
        } else {
            result = new Result(ResultCodeEnum.QUERY_DATA_ERROR, "查询优质服务商数据为空！");
        }
        return result;
    }

    /**
     * 获取服务商入驻实体
     *
     * @param memberId 会员id
     * @return
     */
    @Override
    public Result getSupplierSettedInfo(Long memberId) {
        Result result = null;

        SupplierEntity supplierEntity = new SupplierEntity();

        supplierEntity.setMemberId(memberId);
        supplierEntity.setSettledAuditResult(2);

        GetSupplierListResp supplierListResp = supplierInfoMapper.selectSupplierByKey(supplierEntity);

        if(supplierListResp != null){
            result = new Result(supplierListResp);
        }else{
            result = new Result(ResultCodeEnum.APPEND_DATA_ERROR,"该服务商未入驻！");
        }

        return result;
    }
}
